﻿using HostedServiceDemo.EfContext;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace HostedServiceDemo
{
    internal class QuartzHostedService : IHostedService
    {
        private readonly ILogger _logger;
        private readonly IScheduler _scheduler;
        private readonly EFContext _context;

        public QuartzHostedService(ILogger<QuartzHostedService> logger, IScheduler scheduler, EFContext context)
        {
            _logger = logger;
            _scheduler = scheduler;
            _context = context;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("开始Quartz调度...");

            // 开启调度器
            await _scheduler.Start(cancellationToken);

            var list = await _context.QuartInfo.AsNoTracking().ToListAsync();
            foreach (var item in list)
            {
                // 创建触发器
                var trigger = TriggerBuilder.Create()
                                    .WithIdentity(item.triggerName, item.triggerGroup)
                                    .WithCronSchedule(item.cronExpression)
                                    .Build();

                // 创建任务
                Type type = Type.GetType(item.fullClassName);
                var jobDetail = JobBuilder.Create(type)
                                    .WithIdentity(item.jobName, item.jobGroup)
                                    .Build();

                await _scheduler.ScheduleJob(jobDetail, trigger);
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("停止Quartz调度...");
            await _scheduler.Shutdown(cancellationToken);
        }
    }
}
